
import React, { Component, createRef } from 'react'
import { Button, Space, Dropdown, Menu, message, Modal, Switch, TreeSelect } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import MotionLayout from '@/layouts/MotionLayout';
import { ModuleList, ModuleAdd, ModuleEdit, ModuleDel } from "@/services/module";
import arrayToTree from "array-to-tree";
import treeToList from "tree-to-list";
import UpdateForm from './components/UpdateForm';
import CreateForm from './components/CreateForm';
import IconSelect from '@/components/IconSelect';
import { scriptUrl } from "@/utils/config";
import {
  FormOutlined,
  DeleteOutlined,
  DownOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  CopyOutlined,
  createFromIconfontCN,
} from '@ant-design/icons';
const MyIcon = createFromIconfontCN({
  scriptUrl, // 在 iconfont.cn 上生成
});


const actionRef = createRef();
export default class Module extends Component {
  constructor(props) {
    super(props)

    this.state = {
      options: [],
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
      expandedRowKeys: [],
      selectedRowKeys: [],
      isExpand: true,
      arr: [],
    }
  }
  async handleDeal({ fields, serviceMethod, type = "添加" }) {
    const hide = message.loading(`正在${type}`);
    try {
      const res = await serviceMethod(fields);
      hide();
      if (!res.success) {
        message.error(`${type}失败，${res.result}`);
        return false;
      }
      message.success(`${type}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`${type}异常，${error}`);
      return false;
    }
  }
  async getDataSource(params) {

    const { result, success } = await ModuleList()
    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }

    const options = arrayToTree(
      result.arr.map(item => ({ ...item, value: item.id.toString(), title: item.displayName, fid: item.fid.toString() })),
      { rootID: "0", parentProperty: "fid", customID: "value", childrenProperty: "children" }
    )
    const data = arrayToTree(result.arr, { rootID: "0", parentProperty: "fid", customID: "id", childrenProperty: "children" })
    this.setState({
      arr: result.arr,
      options: [{ value: "0", title: "根目录", children: options },],
      expandedRowKeys: result.arr.map(item => item.id),
      selectedRowKeys: [],
      isExpand: true,
    })
    return {
      data,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '所属模块',
        dataIndex: 'fid',
        hideInTable: true,
        rules: [{
          required: true,
        }],
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<TreeSelect
            treeData={this.state.options}
            placeholder="请选择"
            treeDefaultExpandAll
          />)
        }
      },
      {
        title: '页面名',
        dataIndex: 'moduleName',
        hideInTable: true,
        rules: [{
          required: true,
        }],
      },
      {
        title: '模块名',
        dataIndex: 'displayName',
        rules: [{
          required: true,
        }],
      },
      {
        title: '图标',
        dataIndex: 'icon',
        hideInForm: true,
        render: (_, row) => {
          return (row.icon ? (row.icon.includes("icon-") ? <MyIcon type={row.icon} style={{ fontSize: 18 }} /> :
            null
          ) : null)
        }
      },
      {
        title: '图标',
        dataIndex: 'icon',
        hideInTable: true,
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<IconSelect
            url={scriptUrl}
            placeholder="点击选择或者输入"
          />)
        }
      },
      {
        title: 'URL',
        dataIndex: 'url',
        hideInTable: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: "dateTime",
        hideInForm: true,
      },
      {
        title: '页面名',
        dataIndex: 'moduleName',
        hideInForm: true,
      },
      {
        title: '显示顺序',
        dataIndex: 'orderNum',
        formItemProps: {
          type: "number"
        },
        rules: [{
          required: true,
        }],
      },
      {
        title: '备注',
        dataIndex: 'remark',
        hideInTable: true,
      },
      {
        title: '是否可用',
        dataIndex: 'isEnable',
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Success',
          },
        },
      },

      {
        title: '模块类型',
        dataIndex: 'moduleType',
        valueEnum: {
          0: {
            text: "通用型",
          },
          1: {
            text: '自定义型',
          },
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space>
            <Button
              onClick={async (e) => {
                e.stopPropagation();
                Modal.confirm({
                  title: '是否确认复制?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const success = await this.handleDeal({
                      type: "添加",
                      fields: row,
                      serviceMethod: ModuleAdd,
                    });
                    if (!success) {
                      return;
                    }
                    this.setState({
                      createModalVisible: false,
                    })
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });

              }}
              size="small" type="default" icon={<CopyOutlined />} ></Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                const selectRow = {
                  orderNum: "0",
                  moduleType: "0",
                  isEnable: "true",
                  fid: row.id.toString(),
                }
                this.setState({
                  createModalVisible: true,
                  selectRow,
                })
              }}
              size="small" type="primary" icon={<PlusOutlined />} ></Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();

                const selectRow = {
                  ...row,
                  fid: row.fid.toString(),
                  orderNum: row.orderNum.toString(),
                  moduleType: row.moduleType.toString(),
                  isEnable: row.isEnable.toString(),
                }
                this.setState({
                  updateModalVisible: true,
                  selectRow,
                })
              }}
              size="small" type="primary" icon={<FormOutlined />} ></Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                if (row.children) {
                  message.warn(`请先删除子节点`);
                  return;
                }
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      "id": [
                        row.id
                      ]
                    };
                    const success = await this.handleDeal({
                      type: "删除",
                      fields: idList,
                      serviceMethod: ModuleDel,
                    });
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
          </Space>
        ),
      },
    ];
  }
  createRowSelection() {
    return {
    }
  }
  render() {
    const rowSelection = {
      onSelect: (record, selected, selectedRows) => {
        if (record.children) {
          const dealIdList = [record.id, ...treeToList(record.children, "children").map(item => item.id)];
          if (selected) {
            //选择父节点
            this.setState({
              expandedRowKeys: [...new Set([...this.state.expandedRowKeys, ...dealIdList])],
              selectedRowKeys: [...new Set([...this.state.selectedRowKeys, ...dealIdList])],
            })
          }
          else {

            //反选父节点
            this.setState({
              expandedRowKeys: [...new Set([...this.state.expandedRowKeys, ...dealIdList])],
              selectedRowKeys: this.state.selectedRowKeys.filter(item => !dealIdList.some(sitem => sitem == item)),
            })
          }
        }
        else {
          if (selected) {
            this.setState({
              selectedRowKeys: [...new Set([...this.state.selectedRowKeys, record.id])],
            })
          }
          else {
            this.setState({
              selectedRowKeys: this.state.selectedRowKeys.filter(item => item != record.id),
            })
          }
        }
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        if (selected) {
          this.setState({
            selectedRowKeys: selectedRows.map(item => item.id),
            expandedRowKeys: selectedRows.map(item => item.id),
          })
        }
        else {
          this.setState({
            selectedRowKeys: [],
            expandedRowKeys: [],
          })
        }
      },
      selectedRowKeys: this.state.selectedRowKeys
    };
    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <ProTable
            actionRef={actionRef}
            headerTitle={
              <Switch checked={this.state.isExpand}
                onChange={isChecked => {
                  let rootIdList = [];
                  if (isChecked) {
                    rootIdList = this.state.arr.map(item => item.id);
                  }
                  this.setState({
                    isExpand: isChecked,
                    expandedRowKeys: rootIdList,
                  })
                }}
                unCheckedChildren="全部收起" checkedChildren="全部展开" />
            }
            rowKey="id"
            params={{}}
            request={async (params) => this.getDataSource(params)}
            columns={this.createColumns()}
            rowSelection={rowSelection}
            expandable={{
              expandRowByClick: true,
              expandedRowKeys: this.state.expandedRowKeys,
              onExpand: (expanded, record) => {
                if (expanded) {
                  this.setState({
                    expandedRowKeys: [...new Set([...this.state.expandedRowKeys, record.id])],
                  })
                } else {
                  this.setState({
                    expandedRowKeys: this.state.expandedRowKeys.filter(item => item != record.id)
                  })
                }
              }
            }}
            search={false}
            pagination={false}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => {

              return ([
                <Button type="primary" onClick={() => {
                  const selectRow = {
                    orderNum: "0",
                    moduleType: "0",
                    isEnable: "true",
                    fid: "0",
                  }
                  this.setState({
                    createModalVisible: true,
                    selectRow,
                  })
                }}>
                  <PlusOutlined /> 新建
                          </Button>,
                selectedRowKeys && selectedRowKeys.length > 0 && (
                  <Dropdown
                    overlay={
                      <Menu
                        onClick={async e => {
                          if (e.key === 'remove') {
                            const idList = {
                              "id": selectedRowKeys
                            };
                            Modal.confirm({
                              title: '是否确认删除?',
                              icon: <ExclamationCircleOutlined />,
                              onOk: async () => {
                                const success = await this.handleDeal({
                                  type: "删除",
                                  fields: idList,
                                  serviceMethod: ModuleDel
                                });
                                if (!success) {
                                  return;
                                }
                                if (!actionRef.current) {
                                  return;
                                }
                                actionRef.current.reload();
                              },
                            });
                          }
                        }}
                        selectedKeys={[]}
                      >
                        <Menu.Item key="remove">批量删除</Menu.Item>
                        <Menu.Item key="approval">批量审批</Menu.Item>
                      </Menu>
                    }
                  >
                    <Button>
                      批量操作 <DownOutlined />
                    </Button>
                  </Dropdown>
                ),
              ]);
            }}
            tableAlertOptionRender={() => {
              return (
                <Space>
                  <a onClick={() => {
                    this.setState({
                      selectedRowKeys: []
                    })
                  }}>清空</a>
                </Space>
              );
            }}
          // tableAlertRender={({ selectedRowKeys }) => selectedRowKeys.length == 0 ? false : <div className="ant-pro-table-alert-info-content">
          //   <span>已选择<a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a>项&nbsp;&nbsp;</span>
          // </div>}
          />
        </MotionLayout>
        <CreateForm
          onCancel={() => this.setState({ createModalVisible: false })}
          createModalVisible={this.state.createModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                fid: Number(fieldsValues.fid),
                moduleType: Number(fieldsValues.moduleType),
                orderNum: Number(fieldsValues.orderNum),
                isEnable: fieldsValues.isEnable == "true",
                rank: fieldsValues.fid == "0" ? 1 : this.state.arr.find(item => item.id == Number(fieldsValues.fid)).rank + 1,
              }

              const success = await this.handleDeal({
                type: "添加",
                fields,
                serviceMethod: ModuleAdd,
              });
              if (!success) {
                return;
              }
              this.setState({
                createModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();

            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
            rowSelection={{}}
          />
        </CreateForm>
        <UpdateForm
          onCancel={() => this.setState({ updateModalVisible: false })}
          updateModalVisible={this.state.updateModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                fid: Number(fieldsValues.fid),
                moduleType: Number(fieldsValues.moduleType),
                orderNum: Number(fieldsValues.orderNum),
                isEnable: fieldsValues.isEnable == "true",
                rank: fieldsValues.fid == "0" ? 1 : this.state.arr.find(item => item.id == Number(fieldsValues.fid)).rank + 1,
                id: this.state.selectRow.id,
              }
              if (fields.fid == fields.id) {
                message.warn(`不能属于自己`);
                return;
              }
              const success = await this.handleDeal({
                type: "更新",
                fields,
                serviceMethod: ModuleEdit,
              });
              if (!success) {
                return;
              }
              this.setState({
                updateModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
            rowSelection={{}}
          />
        </UpdateForm>
      </PageHeaderWrapper>
    )
  }
}
